package com.gsc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gsc.domain.ResponseResult;
import com.gsc.domain.dto.UserDto;
import com.gsc.domain.entity.User;
import com.gsc.domain.entity.UserRole;
import com.gsc.domain.vo.PageVo;
import com.gsc.domain.vo.UserInfoVo;
import com.gsc.enums.AppHttpCodeEnum;
import com.gsc.exception.SystemException;
import com.gsc.mapper.UserMapper;
import com.gsc.utils.BeanCopyUtils;
import com.gsc.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import com.gsc.service.UserService;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户表(User)表服务实现类
 *
 * @author makejava
 * @since 2023-02-13 13:56:37
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleServiceImpl userRoleService;

    /**
     * 查询个人中心信息
     * @return
     */
    @Override
    public ResponseResult userInfo() {
        //获取当前用户id
        Long userId = SecurityUtils.getUserId();
        //根据用户id查询用户信息
        User user = getById(userId);
        //封装成UserInfoVo
        UserInfoVo vo = BeanCopyUtils.copyBean(user,UserInfoVo.class);
        return ResponseResult.okResult(vo);
    }

    /**
     * 更新用户信息
     * @param user
     * @return
     *
     * 这里可能会存在问题，有点简略，可以使用security中登录用户
     */
    @Override
    public ResponseResult updateUserInfo(User user) {
        updateById(user);
        return ResponseResult.okResult();
    }

    /**
     * 注册用户业务代码
     * @param user
     * @return
     */
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public ResponseResult register(User user) {
        //对数据进行非空判断 [hasText():字符串 不是 null ，并且不为空，而且不能是空白字符，只有这三个条件同时满足时才 返回 true]
        if(!StringUtils.hasText(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_NULL);
        }
        if(!StringUtils.hasText(user.getPassword())){
            throw new SystemException(AppHttpCodeEnum.PASSWORD_NOT_NULL);
        }
        if(!StringUtils.hasText(user.getEmail())){
            throw new SystemException(AppHttpCodeEnum.EMAIL_NOT_NULL);
        }
        if(!StringUtils.hasText(user.getNickName())){
            throw new SystemException(AppHttpCodeEnum.NICKNAME_NOT_NULL);
        }
        //查询数据库，对数据进行是否存在判断
        if(userNameExist(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }
        if(nickNameExist(user.getNickName())){
            throw new SystemException(AppHttpCodeEnum.NICKNAME_EXIST);
        }
        if(emailExist(user.getEmail())){
            throw new SystemException(AppHttpCodeEnum.EMAIL_EXIST);
        }

        //对密码进行加密处理
        String encodePassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodePassword);
        //存储到数据库中
        save(user);
        return ResponseResult.okResult();
    }

    /**
     * 后台系统查询用户信息
     * @return
     */
    @Override
    public PageVo selectUserList(Integer pageNum, Integer pageSize, User user) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(user.getUserName()),User::getUserName,user.getUserName());
        queryWrapper.like(StringUtils.hasText(user.getPhonenumber()),User::getPhonenumber,user.getPhonenumber());
        queryWrapper.eq(StringUtils.hasText(user.getStatus()),User::getStatus,user.getStatus());
        //分页查询
        Page<User> page = new Page<>(pageNum, pageSize);
        page(page,queryWrapper);
        //封装数据返回
        List<User> records = page.getRecords();
        PageVo pageVo = new PageVo(records,page.getTotal());
        return pageVo;
    }

    @Override
    public ResponseResult addUser(UserDto userDto) {
        //对数据进行非空判断 [hasText():字符串 不是 null ，并且不为空，而且不能是空白字符，只有这三个条件同时满足时才 返回 true]
        if(!StringUtils.hasText(userDto.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_NULL);
        }
        if(!StringUtils.hasText(userDto.getNickName())){
            throw new SystemException(AppHttpCodeEnum.NICKNAME_NOT_NULL);
        }
        if(!StringUtils.hasText(userDto.getPassword())){
            throw new SystemException(AppHttpCodeEnum.PASSWORD_NOT_NULL);
        }

        //查询数据库，对数据进行是否存在判断
        if(userNameExist(userDto.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }
        if(nickNameExist(userDto.getNickName())){
            throw new SystemException(AppHttpCodeEnum.NICKNAME_EXIST);
        }
        if(emailExist(userDto.getEmail())){
            throw new SystemException(AppHttpCodeEnum.EMAIL_EXIST);
        }
        if(emailExist(userDto.getPhonenumber())){
            throw new SystemException(AppHttpCodeEnum.PHONENUMBER_EXIST);
        }
        User user = BeanCopyUtils.copyBean(userDto, User.class);
        //对密码进行加密处理
        String encodePassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodePassword);
        save(user);
        //新增用户所具有的角色(user_role)

        List<UserRole> userRoles = userDto.getRoleIds().stream()
                .map(roleId -> new UserRole(user.getId(), roleId))
                .collect(Collectors.toList());
        userRoleService.saveBatch(userRoles);

        return ResponseResult.okResult();
    }

    @Override
    public void updateUser(UserDto userDto) {
        User user = BeanCopyUtils.copyBean(userDto, User.class);
        updateUserInfo(user);

        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getUserId,user.getId());
        userRoleService.remove(queryWrapper);

        //删除用户角色表‘
        List<UserRole> userRoles = userDto.getRoleIds().stream()
                .map(roleId -> new UserRole(user.getId(), roleId))
                .collect(Collectors.toList());
        //再插入新的
        userRoleService.saveBatch(userRoles);
    }

    /**
     * 判断邮箱在数据库中是否存在
     * @param email
     * @return
     */
    private boolean emailExist(String email) {
        //在数据库中查询用户名相同的个数
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getEmail,email);
        return count(queryWrapper)>0;
    }

    /**
     * 判断昵称在数据库中是否存在
     * @param nickName
     * @return
     */
    private boolean nickNameExist(String nickName) {
        //在数据库中查询用户名相同的个数
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getNickName,nickName);
        return count(queryWrapper)>0;
    }

    /**
     * 判断用户名在数据库中是否存在
     * @param userName
     * @return
     */
    private boolean userNameExist(String userName) {
        //在数据库中查询用户名相同的个数
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,userName);
        return count(queryWrapper)>0;
    }

}
